package com.raising.modules.sys.controller;

import com.raising.framework.controller.BaseController;
import com.raising.utils.JCacheUtils;
import com.raising.utils.ValidateCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping(value = "${frontPath}")
public class ValidateCodeController extends BaseController {
    /**
     * 生成验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        String verifyCode = ValidateCodeUtils.generateTextCode(ValidateCodeUtils.TYPE_NUM_ONLY, 4, null);
        JCacheUtils.put("validateCode",verifyCode);//放入缓存
        request.getSession().setAttribute("validateCode", verifyCode);
        BufferedImage bim = ValidateCodeUtils.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(bim, "JPEG",sos);
        sos.close();
    }
}
